<!--
 * @Descripttion:
 * @version:
 * @Author: ybac
 * @Date: 2022-11-04 10:37:34
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-07-04 15:53:35
-->
<template>
  <j-modal :visible.sync="modal.visible" :width="screenWidth - 100" :title="modal.title"
    :fullscreen.sync="modal.fullscreen" :switchFullscreen="modal.switchFullscreen" @cancelVisible="cancel" :zIndex='99'>
    <template>
      <div class="form-wrap" ref="formRef">
        <a-form :form="form" @submit="submit" class="form">
          <a-row class="form-row" :gutter="[48, 16]">
            <a-col :span="22">
              <a-form-item prop="customCode" :wrapper-col="{ span: 20 }" :label-col="{ span: 4 }">
                <span slot="label"> 客户编号</span>
                <a-input v-if="modal.title == '编辑客户'" disabled placeholder="请输入，不输入则自动生成" v-decorator="['customCode']">
                </a-input>
                <a-input v-else v-decorator="['customCode']" placeholder="请输入，不输入则自动生成" :maxLength="21" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="[48, 16]">
            <a-col :span="22">
              <a-form-item prop="customName" :wrapper-col="{ span: 20 }" :label-col="{ span: 4 }">
                <span slot="label"> 客户名称</span>
                <a-input v-decorator="[
                  'customName',
                  {
                    rules: [{ required: true, message: '请输入' }],
                  },
                ]" placeholder="请输入" :maxLength="50" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="[48, 16]">
            <a-col :span="22">
              <a-form-item prop="notes" :wrapper-col="{ span: 20 }" :label-col="{ span: 4 }">
                <span slot="label">备注</span>
                <a-textarea :auto-size="{ minRows: 4 }" :maxLength="100" v-decorator="['notes']" placeholder="请输入" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="[48, 16]">
            <a-col :span="22" v-for="(p, index) in formTypeExtendedFields" :key="index">
              <a-form-item :required="p.fieldMust == 2" :wrapper-col="{ span: 20 }" :label-col="{ span: 4 }">
                <span slot="label">{{ p.fieldName }}
                  <a-tooltip v-if="p.explanationPrompt" :title="p.explanationPrompt" class="toopic-icon"
                    :getPopupContainer="getPopupContainer">
                    <a-icon type="info-circle" style="color: rgba(0, 0, 0, 0.45)" />
                  </a-tooltip>
                  <!--                  {{ '：' }}-->
                </span>
                <a-input :disabled="p.fieldMust == 1" :placeholder="p.placeholder" v-if="p.fieldType == 1" v-decorator="[
                  'extDataJson.' + p.fieldKey,
                  { rules: [{ required: p.fieldMust == 2, message: '请输入内容' }] },
                ]">
                </a-input>

                <a-textarea :disabled="p.fieldMust == 1" :placeholder="p.placeholder" v-decorator="[
                  'extDataJson.' + p.fieldKey,
                  { rules: [{ required: p.fieldMust == 2, message: '请输入内容' }] },
                ]" v-if="p.fieldType == 2" :auto-size="{ minRows: 3, maxRows: 5 }">
                </a-textarea>

                <a-input-number style="width: 100%" :disabled="p.fieldMust == 1" :placeholder="p.placeholder"
                  :formatter="(value) => value.substr(0, p.fieldLength)"
                  :parser="(value) => value.substr(0, p.fieldLength)" :min="0" :precision="0" v-if="p.fieldType == 3"
                  v-decorator="[
                    'extDataJson.' + p.fieldKey,
                    { rules: [{ required: p.fieldMust == 2, message: '请输入内容' }] },
                  ]">
                </a-input-number>

                <a-input-number v-if="p.fieldType == 4" :step="0.0001" style="width: 100%" :disabled="p.fieldMust == 1"
                  :placeholder="p.placeholder" :min="0.0001" :max="getMaxValueForDigits(p.fieldLength * 1)" v-decorator="[
                    'extDataJson.' + p.fieldKey,
                    { rules: [{ required: p.fieldMust == 2, message: '请输入内容' }] },
                  ]" :formatter="(value) => onInput(value)" />

              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </template>
    <template slot="footer">
      <a-button key="back" @click="cancel"> 取消 </a-button>
      <a-button key="submit" type="primary" @click="submit" :loading="loadingForm"> 确定 </a-button>
    </template>
  </j-modal>
</template>

<script>
import JAreaLinkage from '@comp/jeecg/JAreaLinkage'
import { APILX } from '@/api/requestLx'
export default {
  name: 'customerForm',
  props: ['tenantId'],
  components: {
    JAreaLinkage,
  },
  data() {
    return {
      form: this.$form.createForm(this, { name: 'coordinated' }),
      modal: {
        title: '新建客户',
        visible: false,
        fullscreen: false,
        switchFullscreen: false,
      },
      submitApi: '',
      loadingForm: false,
      queryId: '',
      treeData: [],
      parentId: '',
      formTypeExtendedFields: [],
      screenWidth: document.body.clientWidth, // 屏幕宽
    }
  },
  methods: {
    onInput(event) {
      console.log(event, 'event')
      let value = event + ''
      // 截断小数点后超过4位的部分
      if (value.includes('.')) {
        let parts = value.split('.')
        if (parts[1].length > 4) {
          value = parts[0] + '.' + parts[1].substring(0, 4)
        }
      } else {
        value = event
      }
      console.log(value, 'valuevalue')
      return value
    },
    getMaxValueForDigits(digitCount) {
      console.log(digitCount, 'digitCount')

      if (digitCount <= 0) {
        throw new Error('Digit count must be a positive integer.')
      }
      console.log((Math.pow(10, digitCount) - 1) + 0.9999)

      return (Math.pow(10, digitCount) - 1) + 0.9999
    },
    getPopupContainer() {
      return this.$refs.formRef
    },
    changeParent(v) {
      this.parentId = v
      this.$nextTick(() => {
        this.form.validateFields(['customCode'])
      })
    },
    async formTypeExtendedFieldList() {
      let res = await APILX.formTypeExtendedFieldList({ formType: 1, id: this.parentId })
      if (res.code == 200 && res.result) {
        this.formTypeExtendedFields = res.result
        console.log('res.result0000000', res.result)
      }
    },
    // 新增表单
    open(pid) {
      this.modal.title = '新建客户'
      this.submitApi = ''
      this.parentId = pid
      this.formTypeExtendedFieldList()
      this.modal.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue({
          parentId: pid,
        })
      })
    },
    // 编辑表单
    editor(v) {
      this.modal.title = '编辑客户'
      this.submitApi = ''
      let resForm = v
      this.parentId = v.id
      this.formTypeExtendedFieldList()
      this.modal.visible = true
      setTimeout(() => {
        this.form.setFieldsValue({
          tenantId: resForm.tenantId,
          customCode: resForm.customCode,
          customName: resForm.customName,
          notes: resForm.notes,
          ...v,
        })
      }, 200)
    },
    // 提交表单
    submit() {
      this.loadingForm = true
      this.form.validateFields((err, formValues) => {
        if (!err) {
          let params = {
            customCode: formValues.customCode,
            customName: formValues.customName,
            notes: formValues.notes,
            extDataJson: formValues.extDataJson,
          }
          let api = APILX.getSaleCustomInfoAdd
          if (this.modal.title == '编辑客户') {
            api = APILX.getSaleCustomInfoEdit
            params = {
              ...params,
              id: this.parentId,
            }
          }
          let  extendedFields = this.formTypeExtendedFields
          console.log(Array.isArray(extendedFields), 'formTypeExtendedFields')
          let extDataJson = formValues.extDataJson
          extendedFields.forEach(item=>{
            console.log(item,'iiii',formValues.extDataJson)
            for (const itemKey in extDataJson) {
              if(itemKey==item.fieldKey&&item.fieldMust==1){
                console.log(itemKey, 'itemKeyitemKey')
                extDataJson[itemKey] = item.placeholder
              }
            }
          })

          api(params)
            .then((res) => {
              if (res.success) {
                this.$antdMessage.success(res.message)
                this.$emit('refresh')
                this.cancel()
              } else {
                this.$antdMessage.error(res.message)
              }
              this.loadingForm = false
            })
            .catch((err) => { })
        } else {
          this.loadingForm = false
        }
      })
    },
    // 关闭表单
    cancel() {
      this.form.resetFields()
      this.loadingForm = false
      this.modal.visible = false
    },
  },
}
</script>

<style lang="less" scoped>
.ant-message {
  z-index: 99999 !important;
}

/deep/.ant-modal-body {
  padding: 12px !important;

  .ant-form-item {
    margin-bottom: 0;
  }
}

.form-wrap {
  background: #fff;
  height: 100%;
  padding: 24px;
  overflow-y: scroll;

  .code-btn {
    position: absolute;
    right: 0;
    top: -50.5px;
  }
}

/deep/ .toopic-icon {
  //  .ant-tooltip {
  //     z-index: 99999999;
  //   }
}
</style>
